import App from 'app';
import React, { useEffect } from 'react';
import Queue from 'lib/base/queue';
import { getLogger } from 'utils';
import { gsap, Quad, Cubic } from 'gsap';

import './style.scss';

const logger = getLogger('Preloader', '#c50');

export default function (props) {
	const el = React.createRef();
	const cen = React.createRef();
	const prog = React.createRef();

	const mounted = () => {
		let queue = new Queue({
			assetsURL: '',
			videosURL: ''
		});

		// props
		// array files
		const assets = props.assetsList;

		queue.on('progress', (e) => {
			//  ~~(e.loaded * 100);
			gsap.to(prog.current, 0.3, {
				scaleX: e.loaded * 0.2,
				ease: Quad.easeInOut
			});
		});

		queue.on('complete', (e) => {
			// maybe cache assets here
			const results = e.target.getResults();

			e.target.destroy();
			e.target = null;
			queue = null;

			App.cachedAssests = results;
			App.data = results['site'];

			// <remove>
			// logger('App.data..', results, App.data);
			// </remove>

			next();
		});
		queue.load(assets);
	};

	const next = () => {
		gsap.to(prog.current, 0.65, {
			scaleX: 1,
			ease: Cubic.easeIn
		});

		// do some prep tricks here
		gsap.delayedCall(0.65, done);
	};

	const done = () => {
		gsap.to(el.current, 0.35, {
			autoAlpha: 0
		});

		gsap.delayedCall(0.1, () => {
			App.trigger('startup:app');
		});

		// probably do some tricks during preloading

		gsap.delayedCall(0.3, () => {
			App.trigger('startup:end');
		});
	};

	const listItems = [];
	for (let i = 0; i < App.fontsLength; ++i) {
		listItems.push(
			<div className={'f' + i + 1} key={'f' + i}>
				&nbsp;
			</div>
		);
	}

	useEffect(() => {
		mounted();
		return () => {
			// logger('destroyed..');
		};
	}, []);

	return (
		<div className='Preloader' ref={el}>
			<div ref={cen} className='cen'>
				<div className='bar'>
					<div ref={prog} className='progress'></div>
				</div>
			</div>

			<div className='fonts'>{listItems}</div>
		</div>
	);
}
